% 
% @(#)real_Buffer.m	1.1  3/16/88
%
import _VectorOfCharObject from "Builtins"
export _BufferObject to "Builtins"
const _BufferObject == immutable object _BufferObject
  export getSignature, create
  const BufferType == type BufferType
    operation write
    operation addChar [Character]
    operation addString [String]
    operation Pad [Character, Integer]
  end BufferType

  function getSignature -> [r : Signature]
    r <- BufferType
  end getSignature

  operation create [myfd : Integer]-> [r : BufferType]
    r <- object aBuffer
      export addChar, addString, write, pad
      const BUFSIZE == 1024
      monitor
	const buf == _VectorOfCharObject.create[BUFSIZE]
	var nextToFillIndex : Integer <- 0
	operation write 
	  if nextToFillIndex > 0 then
	    primitive 017 [] <- [myfd, buf, nextToFillIndex]
	    nextToFillIndex <- 0
	  end if
	end write
	operation addChar [c : Character]
	  buf(nextToFillIndex) := c
	  nextToFillIndex <- nextToFillIndex + 1
	  if nextToFillIndex >= BUFSIZE or c = '\^J' then
	    primitive 017 [] <- [myfd, buf, nextToFillIndex]
	    nextToFillIndex <- 0
	  end if
	end addChar
	operation addString [s : String]
	  var i : Integer <- 0
	  var limit : Integer <- s.length
	  var index : Integer <- nextToFillIndex
	  var c : Character
	  loop
	    exit when i >= limit
	    c <- s(i)
	    buf(index) := c
	    index <- index + 1
	    i <- i + 1
	    if index >= BUFSIZE or c = '\^J' then
	      primitive 017 [] <- [myfd, buf, index]
	      index <- 0
	    end if
	  end loop
	  nextToFillIndex <- index
	end addString
	operation Pad [c : Character, w : Integer]
	  var i : Integer <- 0
	  var limit : Integer <- w
	  var index : Integer <- nextToFillIndex
	  loop
	    exit when i >= limit
	    buf(index) := c
	    index <- index + 1
	    i <- i + 1
	    if index >= BUFSIZE then
	      primitive 017 [] <- [myfd, buf, index]
	      index <- 0
	    end if
	  end loop
	  nextToFillIndex <- index
	end Pad
      end monitor
    end aBuffer
  end create
end _BufferObject
